<template>
  <div>
    <top-footer>
      <template #search>
        <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" inline label-width="90px">
          <px-form-item label="科室">
            <px-select v-model="queryParams.className" clearable disabled filterable>
              <px-option v-for="item in classNameList" :key="item.id" :label="item.itemName" :value="item.itemValue" />
            </px-select>
          </px-form-item>

          <px-form-item label="文档编码/名称">
            <px-input v-model="queryParams.commonValue" clearable />
          </px-form-item>
          <px-form-item label="交班人" prop="handoverPerson">
            <px-select-v2 v-model="queryParams.handoverPerson" :options="userList" clearable filterable placeholder="请选择" />
          </px-form-item>
          <px-form-item label="接班人">
            <px-select-v2 v-model="queryParams.successorPerson" :options="userList" clearable filterable placeholder="请选择" />
          </px-form-item>
          <px-form-item label="交接状态">
            <px-select v-model="queryParams.handoverStatus" clearable filterable>
              <px-option v-for="item in statusList" :key="item.id" :label="item.itemName" :value="item.itemValue" />
            </px-select>
          </px-form-item>
          <px-form-item label="值班日期" prop="handoverTime" style="width: 528px">
            <!-- <px-date-picker
              v-model="queryParams.handoverStartTime"
              clearable
              type="datetime"
              :editable="false"
              format="YYYY/MM/DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择开始时间"
            /> -->
            <px-date-picker
              v-model="queryParams.handoverTime"
              clearable
              type="daterange"
              range-separator="至"
              start-placeholder="请选择开始时间"
              end-placeholder="请选择结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </px-form-item>
          <!-- <px-form-item label="结束时间" prop="endTime">
            <px-date-picker
              v-model="queryParams.handoverEndTime"
              clearable
              type="datetime"
              :editable="false"
              format="YYYY/MM/DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="new Date(2000, 1, 1, 23, 59, 59)"
              placeholder="请选择结束时间"
            />
          </px-form-item> -->
          <px-form-item class="option-item">
            <px-button type="primary" @click="searchAction">查询</px-button>
            <px-button @click="resetQuery">重置</px-button>
          </px-form-item>
        </px-form>
      </template>
      <template #btn>
        <div class="table-btn-group">
          <px-button v-has="`${queryParams.className}_HANDOVER_LIST_ADD`" type="primary" @click="gotoTemplate">新建交接班</px-button>
          <px-button v-has="`${queryParams.className}_HANDOVER_LIST_BATCH_DELETE`" @click="deleteRecordAction">批量删除</px-button>
          <px-button v-has="`${queryParams.className}_HANDOVER_LIST_BATCH_EXPORT`" @click="exportRecordAction">批量导出</px-button>
        </div>
      </template>
      <template #table="{ height }">
        <px-table
          v-loading="loading"
          :data="tableData"
          :height="height"
          border
          style="width: 100%"
          :show-overflow-tooltip="true"
          @selection-change="selectionChange"
        >
          <template #empty>
            <px-empty />
          </template>
          <px-table-column type="selection" fixed width="40" prop="selection" align="center" />
          <px-table-column label="序号" width="60" align="center" fixed="left">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>

          <!-- <px-table-column prop="reportCode" label="文档编码" min-width="120" />
          <px-table-column prop="reportName" label="文档名称" min-width="120" /> -->
          <px-table-column prop="handoverPerson" label="交班人" min-width="80">
            <template #default="scope">
              <UserName :userId="scope.row.handoverPerson" :userList="allUserList" />
            </template>
          </px-table-column>
          <px-table-column prop="successorPerson" label="接班人" min-width="80">
            <template #default="scope">
              <UserName :userId="scope.row.successorPerson" :userList="allUserList" />
            </template>
          </px-table-column>
          <px-table-column prop="handoverWorkShift" label="值班时间" min-width="100" />
          <px-table-column prop="handoverTime" label="值班日期" min-width="100">
            <template #default="scope">{{ dayjs(scope.row.handoverTime).format("YYYY-MM-DD") }}</template>
          </px-table-column>
          <px-table-column prop="handoverStatus" label="交接状态" min-width="100">
            <template #default="scope">
              <ApprovalStatus :status="scope.row.handoverStatus || 'UN_SUBMITTED'" />
            </template>
          </px-table-column>
          <px-table-column prop="signStatus" label="签核状态" min-width="100">
            <template #default="scope">
              <ApprovalStatus type="SIGN" :status="scope.row.signStatus" />
            </template>
          </px-table-column>
          <px-table-column label="操作" align="center" width="160px" fixed="right">
            <template #default="scope">
              <px-tooltip effect="dark" content="详情" placement="top">
                <px-button v-has="`${queryParams.className}_HANDOVER_LIST_ITEM_VIEW`" link type="primary" @click="handleDetail(scope.row)">
                  <px-icon><Document /></px-icon>
                </px-button>
              </px-tooltip>
              <px-tooltip effect="dark" content="编辑" placement="top">
                <px-button v-has="`${queryParams.className}_HANDOVER_LIST_ITEM_EDIT`" link type="primary" @click="handleEdit(scope.row)">
                  <px-icon>
                    <EditPen />
                  </px-icon>
                </px-button>
              </px-tooltip>
              <px-tooltip effect="dark" content="删除" placement="top">
                <px-button v-has="`${queryParams.className}_HANDOVER_LIST_ITEM_DELETE`" link type="primary" @click="handleDelete(scope.row)">
                  <px-icon>
                    <Delete color="red" />
                  </px-icon>
                </px-button>
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
      </template>
      <template #foot>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @pagination="queryTable"
        />
      </template>
    </top-footer>
    <px-dialog v-model="editDialogVisible" title="编辑" width="500" @close="closeDialog">
      <px-form ref="formRef" :model="editFormParams" label-width="80px" label-position="right" :rules="editRules">
        <px-form-item label="文档编码" prop="reportCode">
          <px-input v-model="editFormParams.reportCode" maxlength="30" />
        </px-form-item>
        <px-form-item label="文档名称" prop="reportName">
          <px-input v-model="editFormParams.reportName" maxlength="60" />
        </px-form-item>
        <px-form-item label="交班人" prop="handoverPerson">
          <UserName :userId="editFormParams.handoverPerson" :userList="userList" />
        </px-form-item>
        <px-form-item label="接班人" prop="successorPerson">
          <UserName :userId="editFormParams.successorPerson" :userList="userList" />
        </px-form-item>
        <px-form-item label="值班日期" prop="handoverTime">
          <px-input v-model="editFormParams.handoverTime" disabled />
        </px-form-item>
        <px-form-item label="值班时间" prop="handoverWorkShift">
          <px-input v-model="editFormParams.handoverWorkShift" disabled />
        </px-form-item>
      </px-form>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="closeDialog">取消</px-button>
          <px-button type="primary" @click="editSubmit()"> 确定 </px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  userlistPage,
  addReportRecord,
  deleteHandoverRecord,
  queryHandoverRecord,
  updateHandoverRecord,
  queryChildByTypeCodeAndItemValue,
  exportHandoverList
} from "@/api/handover";
import { onMounted, onUnmounted, reactive, toRefs, ref, computed, nextTick, getCurrentInstance } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { getEmployeeIdAndNameByClassCode } from "@/utils/pengxi";
import { useRouter } from "vue-router";
import { useNav } from "@/layout/hooks/useNav";
import TopFooter from "../../report/components/TopFooter.vue";
import { useRouterStoreHook } from "@/store/modules/router";
import ApprovalStatus from "../components/ApprovalStatus.vue";
import UserName from "../components/UserName.vue";
import dayjs from "dayjs";
import { getToken } from "@/utils/auth";

const routerStore = useRouterStoreHook();

defineOptions({
  name: "COMMON_REPORT_TEMPLATE"
});

const router = useRouter();

const userList = ref([]);
const allUserList = ref([]);
const statusList = ref([]);
const classNameList = ref([]);
const tableData = ref([]);
const loading = ref(false);
const total = ref(10);
const editDialogVisible = ref(false);
const uploadDialogVisible = ref(false);
const formRef = ref();
const editFormParams = reactive({});
const editRules = reactive({
  site: [{ default: "" }],
  fab: [{ default: "" }],
  area: [{ default: "" }],
  rmsModelId: [{ default: "" }]
});
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  className: routerStore.getSubject === "ALL" ? "" : routerStore.getSubject,
  handoverStatus: "",
  commonValue: "",
  handoverPerson: "",
  successorPerson: "",
  handoverTime: "",
  handoverStartTime: "",
  handoverEndTime: ""
});
const getUserList = async () => {
  const res = await userlistPage({ pageSize: 2000 }); //ELECTRICTITY
  allUserList.value = res.map(item => ({ value: item.userId, label: item.username + "-" + item.realName, phone: item.phone, userId: item.userId }));
  userList.value = await getEmployeeIdAndNameByClassCode([queryParams.className]);
  // userList.value = res.map(item => ({ label: item.realName, value: item.userId }));
  queryTable();
};

const getClassNameList = async () => {
  const res = await queryChildByTypeCodeAndItemValue({ typeCode: "className" });
  classNameList.value = res;
};
const getStatusList = async () => {
  const res = await queryChildByTypeCodeAndItemValue({ typeCode: "HANDOVER_STATUS" });
  statusList.value = res;
};
const searchAction = () => {
  queryParams.pageNum = 1;
  queryTable();
};
// http://{host}:{port}/webroot/decision/sp/client/api/v3/entry?keyword=目录&entry=["一级目录","二级目录"]
const queryTable = async () => {
  try {
    loading.value = true;
    queryParams.handoverStartTime = queryParams?.handoverTime?.[0] || "";
    queryParams.handoverEndTime = queryParams?.handoverTime?.[1] || "";
    const res = await queryHandoverRecord(queryParams);
    tableData.value = res?.data || [];
    total.value = res?.total;
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};
function resetQuery() {
  queryParams.pageNum = 1;
  queryParams.pageSize = 20;
  queryParams.className = routerStore.getSubject === "ALL" ? "" : routerStore.getSubject;
  queryParams.handoverStatus = "";
  queryParams.commonValue = "";
  queryParams.handoverPerson = "";
  queryParams.successorPerson = "";
  queryParams.handoverStartTime = "";
  queryParams.handoverEndTime = "";
  queryParams.handoverTime = "";
  queryTable();
}
const getTemplateName = () => {
  let subject = routerStore.getSubject === "ALL" ? "" : routerStore.getSubject;
  let t_name = "";
  switch (subject) {
    case "ELECTRICTITY":
      t_name = "电科交接簿";
      break;
    case "GAS":
      t_name = "气化科交接簿";
      break;
    case "WATER":
      t_name = "水科交接簿";
      break;
    case "MACHINE":
      t_name = "机械科交接簿";
      break;
    default:
      break;
  }
  return encodeURIComponent(encodeURIComponent(t_name)) + ".cpt";
};
const gotoTemplate = () => {
  const path = "/fullScreen/handleover/detail";
  let tpl_name = getTemplateName();
  const query = {
    template: tpl_name,
    op: "write"
  };
  const params = { path, query };
  const { href } = router.resolve(params);
  window.open(href, "_blank");
};

const handleDetail = row => {
  if (row.singleCode) {
    const path = "/fullScreen/handleover/detail";
    const query = {
      template: encodeURIComponent(encodeURIComponent(row.moduleName)) + ".cpt",
      op: "write",
      singleCode: row.singleCode,
      id: row.id
    };
    const params = { path, query };
    const { href } = router.resolve(params);
    window.open(href, "_blank");
  }
};
const handleEdit = row => {
  editDialogVisible.value = true;
  editFormParams.id = row.id;
  editFormParams.reportName = row.reportName;
  editFormParams.reportCode = row.reportCode;
  editFormParams.handoverPerson = row.handoverPerson;
  editFormParams.successorPerson = row.successorPerson;
  editFormParams.handoverTime = dayjs(row.handoverTime).format("YYYY-MM-DD");
  editFormParams.handoverWorkShift = row.handoverWorkShift;
};
const handleDelete = row => {
  PxMessageBox.confirm(`是否该条记录数据？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteHandoverRecord({ ids: [row.id] });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};

const closeDialog = () => {
  editDialogVisible.value = false;
  uploadDialogVisible.value = false;
};

const selectedRows = ref([]);
const selectionChange = val => {
  selectedRows.value = val;
};
const deleteRecordAction = () => {
  if (selectedRows.value.length == 0) {
    PxMessage.error("请先选择要删除的数据！");
    return;
  }
  let ids = selectedRows.value.map(v => v.id);
  PxMessageBox.confirm(`是否这些记录数据？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteHandoverRecord({ ids });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
const { proxy }: any = getCurrentInstance();
const { VITE_FANRUAN_BASE_URL } = import.meta.env;
const { username } = useNav();
const exportRecordAction = async () => {
  if (selectedRows.value.length == 0) {
    PxMessage.error("请先选择要导出的数据！");
    return;
  }
  let t_name = getTemplateName();
  let baseUrl = "";
  baseUrl = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=${t_name}&user=${username.value}&facCode=${localStorage.getItem("facCode") || ""}`;

  if (queryParams.className == "WATER" || queryParams.className == "MACHINE") {
    baseUrl = `${baseUrl}&token=${getToken().accessToken}&ifpHost=${window.location.protocol}//${window.location.hostname}`;
  }
  // 循环singlecode 打开连接
  selectedRows.value.forEach(v => {
    let s = v.handoverWorkShift.substring(0, 2); //只取白班和夜班
    let file_name = `${v.moduleName}-${v.handoverTime}-${s}`;
    let url = `${baseUrl}&singleCode=${v.singleCode}&format=excel&extype=simple&__filename__=${file_name}`;
    window.open(url);
  });
};
const editSubmit = () => {
  formRef.value?.validate(async (valid, fields) => {
    if (valid) {
      let res = await updateHandoverRecord({ ...editFormParams });
      PxMessage.success("更新成功");
      closeDialog();
      queryTable();
    } else {
      console.log("error submit!", fields);
    }
  });
};

onMounted(() => {
  getUserList();
  getStatusList();
  getClassNameList();
  window.addEventListener("storage", e => {
    if (e.key != "listen_report_record_delete") return;
    queryTable();
    localStorage.removeItem("listen_report_record_delete");
  });
});
onUnmounted(() => {
  console.log("in unmount");
});
</script>
<style scoped lang="scss">
:deep(.px-select) {
  width: 100%;
}

:deep(.px-input) {
  width: 100%;
}

.table-btn-group {
  .px-button {
    margin-left: 8px;

    &:first-child {
      margin-left: 0;
    }
  }
}

.template-content {
  width: 100%;
}

.template-list {
  display: flex;
  flex-wrap: wrap;

  .temp-item {
    position: relative;
    width: 250px;
    height: 160px;
    margin-right: 24px;
    margin-bottom: 24px;
    cursor: pointer;
    background: blue;

    &.isLast {
      margin-right: 0;
    }

    .name {
      position: absolute;
      bottom: 40px;
      left: 5%;
      width: 90%;
      text-align: center;
    }
  }
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 13px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

.px-icon {
  font-size: 16px !important;
}

:deep(.px-dialog__body) {
  padding: 0 25px;
}

:deep(.px-table__cell) {
  height: 42px;
  padding: 8px 0;
}

:deep(.cell) {
  line-height: 1.2;
}
</style>
